package com.kdgc.power.file.service;

import com.kdgc.power.common.util.StringUtil;
import com.kdgc.power.fw.bean.TreeNode;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FileService {
    public Object findByParentDisk(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        List<TreeNode> fileList = new ArrayList<>();
        if (StringUtil.isNotEmpty(files)) {
            List<File> sorted = Arrays.stream(files).sorted((o1, o2) -> {
              if(o1.isDirectory()&&o2.isFile()){
                  return -1;
              }else {
                  return  String.CASE_INSENSITIVE_ORDER.compare(o1.getName(),o2.getName());
              }
            }).collect(Collectors.toList());
            for (File child : sorted) {
                TreeNode treeNode = new TreeNode();
                treeNode.setName(child.getName());
                treeNode.setPath(child.getAbsolutePath());
                if (StringUtil.isNotEmpty(child) && StringUtil.isEmpty(child.list())) {
                    treeNode.setIsLeaf(true);
                }
                if (StringUtil.isNotEmpty(child) && child.isDirectory()) {
                    treeNode.setExtend1("directory");
                }
                if (StringUtil.isNotEmpty(child) && child.isFile()) {
                    treeNode.setExtend1("file");
                }
                fileList.add(treeNode);
            }
        }
        return fileList;

    }
}